#include "Impartit.h"
#include "Putere.cpp"
long double Impartit::calcul(long double aux1, long double aux2)
{
    if (ISZERO(aux2))
    {
        std::cout<<"Impartire cu 0";
        return 0;
    }

    return aux1 / aux2;
}

long double Impartit::calcul()
{
    if (!fStang || !fDrept)
        exit(1);

    return calcul(fStang->calcul(), fDrept->calcul());
}

char *Impartit::derivare()
{
    char *aux1, *aux11, *aux2, *aux22, *aux, *aux00, *aux01, *aux02, *aux03;

    if (!fStang || !fDrept)
        exit(1);

    aux1 = fStang->derivare();
    aux11 = fStang->toString();
    aux2 = fDrept->derivare();
    aux22 = fDrept->toString();

    aux00 = Inmultit::concatTermeni(aux1, aux11);
    aux01 = Inmultit::concatTermeni(aux2, aux22);
    aux02 = Minus::concatTermeni(aux00, aux01);
    aux03 = Putere::concatTermeni(aux2, "2");
    aux = concatTermeni(aux02, aux03);

    delete aux1; delete aux2; delete aux11; delete aux22;
    delete aux00; delete aux01; delete aux02; delete aux03;
    return aux;
}

long double Impartit::calculDerivata()
{
    long double aux;

    if (!fStang || !fDrept)
        exit(1);

    return Minus::calcul(Inmultit::calcul(fStang->calculDerivata(),  aux),
           Impartit::calcul(Impartit::calcul(Inmultit::calcul(fDrept->calculDerivata(),
                fStang->calcul()), aux), aux));
}

char *Impartit::toString()
{
    char *aux1, *aux2, *aux;

    if (!fStang || !fDrept)
        exit(1);

    aux1 = fStang->toString();
    aux2 = fDrept->toString();

    aux = new char[strlen(aux1) + strlen(aux2) + 4];

    concatTermeni(aux1, aux2);
    delete aux1; delete aux2;

    return aux;
}

char *Impartit::concatTermeni(char *aux1, char *aux2)
{
    char *aux;

    if (!strcmp(aux1, "0"))
        aux = cpystr("0");
    else if (!strcmp(aux2, "1")) aux = cpystr(aux1);
    else
    {
        aux = new char[strlen(aux1) + strlen(aux2) + 4];
        strcpy(aux, "(");
        strcat(aux, aux1); strcat(aux, "/"); strcat(aux, aux2); strcat(aux, ")");
    }
    return aux;
}
